"""
Case Type   : 数据库兼容性
Case Name   : 通过DatabaseMetaData.getPrimaryKeys(),getIndexInfo()获取分区表的pk,index信息
Create At   : 2024/07/26
Owner       : lvlintao666
Description :
    1.创建表
    2.scp相关java代码
    3.编译java代码
    4.运行java脚本
    5.清理环境
Expect      :
    1.创建库表成功
    2.scp成功
    3.编译成功
    4.运行成功
    5.清理成功
History     :
    Modified by peilinqian at 2024-12-5:优化用例连跑失败问题
"""

import os
import time
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class DatabaseMetaDataTestCase(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)}:start----')
        self.pri_root = Node('PrimaryRoot')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_dbuser = Node(node='PrimaryDbUser')
        self.com = Common()
        self.constant = Constant()
        self.schema_name = "schema_jdbc_databasemetadata_case0001"
        self.table_name = "t_jdbc_databasemetadata_case0001"
        self.username = self.pri_root.db_user
        self.jar_name, self.jar_path = self.com.get_jdbc('postgresql')
        self.target_path = os.path.join(macro.DB_BACKUP_PATH, 'JDBC_test')
        self.java_name = "Opengauss_Function_JDBC_DatabaseMetaData_Case0001"
        self.assert_flag = f"--------get primaryKey begin\n" \
                           f"columnIndex: 1 , columnName: col_pk\n" \
                           f"--------get primaryKey end\n" \
                           f"--------get index info begin\n" \
                           f"columnIndex: {self.table_name}_pkey , " \
                           f"columnName: col_pk\n" \
                           f"--------get index info end"

    def test_main(self):
        step_txt = '----step1: 创建指定数据库,创建分区表; expect:创建成功----'
        self.log.info(step_txt)
        create_sql = f"drop schema if exists {self.schema_name};" \
                     f"create schema {self.schema_name};"
        self.log.info(create_sql)
        create_result = self.pri_sh.execut_db_sql(create_sql)
        self.log.info(create_result)
        self.assertIn(self.constant.CREATE_SCHEMA_SUCCESS_MSG, create_result,
                      '执行失败' + step_txt)

        c_t_sql = f"CREATE TABLE {self.schema_name}.{self.table_name} " \
                  f"(col_pk numeric NOT NULL primary key," \
                  f"partition_col character varying(30) NOT NULL)" \
                  f"WITH (orientation=row, compression=no)" \
                  f"PARTITION BY LIST (partition_col)" \
                  f"(PARTITION partition_col_id_0100 VALUES ('0100')," \
                  f"PARTITION partition_col_id_0110 VALUES ('0110')," \
                  f"PARTITION partition_col_id_other VALUES (DEFAULT) );"
        self.log.info(c_t_sql)
        c_t_result = self.pri_sh.execut_db_sql(c_t_sql)
        self.log.info(c_t_result)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, c_t_result,
                      '执行失败' + step_txt)

        step_txt = '----step2: scp相关java; expect:创建成功----'
        self.log.info(step_txt)
        self.com.scp_file(self.pri_root, f'{self.java_name}.java',
                          self.target_path)
        check_cmd = f'ls {self.target_path}'
        check_result = self.pri_root.sh(check_cmd).result()
        self.assertIn(self.java_name, check_result, '执行失败' + step_txt)

        step_txt = '----step3: 编译java文件; expect:编译成功----'
        self.log.info(step_txt)
        self.pri_root.scp_put(self.jar_path,
                              os.path.join(self.target_path, self.jar_name))
        cmd = f"javac -encoding utf-8 -cp " \
              f"{os.path.join(self.target_path, self.jar_name)} " \
              f"{os.path.join(self.target_path, f'{self.java_name}.java')}"
        self.log.info(cmd)
        javac_result = self.pri_root.sh(cmd).result()
        self.log.info(javac_result)
        self.assertEqual('', javac_result, "执行失败" + step_txt)
        time.sleep(3)

        step_txt = '----step4:运行java预编译代码;expect:运行成功-----'
        self.log.info(step_txt)
        java_cmd = f"cd {self.target_path};" \
                   f"java -cp {os.path.join(self.target_path, self.jar_name)}" \
                   f":{self.target_path} {self.java_name} " \
                   f"{self.pri_dbuser.db_host}:{self.pri_dbuser.db_port} " \
                   f"{self.pri_dbuser.db_name} {self.pri_dbuser.db_user} " \
                   f"{self.pri_dbuser.db_password} {self.schema_name} " \
                   f"{self.table_name}"
        self.log.info(java_cmd)
        java_result = self.pri_root.sh(java_cmd).result()
        self.log.info(java_result)
        self.assertIn(self.assert_flag, java_result, "执行失败" + step_txt)

    def tearDown(self):
        step_txt = "----step5:环境清理，恢复参数;expect:环境清理成功，恢复参数成功----"
        self.log.info(step_txt)
        drop_cmd = f"drop table {self.schema_name}.{self.table_name} cascade;" \
                   f"drop schema {self.schema_name};"
        self.log.info(drop_cmd)
        drop_result = self.pri_sh.execut_db_sql(drop_cmd)
        self.log.info(drop_result)

        step_txt2 = '----清理编译脚本; expect:清理成功----'
        self.log.info(step_txt2)
        file_rm_cmd = f'rm -rf {self.target_path};' \
            f'if [ -d {self.target_path} ]; ' \
            f'then echo "exists"; else echo "not exists"; fi'
        self.log.info(file_rm_cmd)
        file_rm_result = self.pri_root.sh(file_rm_cmd).result()
        self.log.info(file_rm_result)

        self.log.info(f'----{os.path.basename(__file__)}:end----')
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, drop_result,
                      '执行失败' + step_txt)
        self.assertIn(self.constant.DROP_SCHEMA_SUCCESS_MSG, drop_result,
                      '执行失败' + step_txt)
        self.assertEqual('not exists', file_rm_result, "执行失败" + step_txt2)
